import storage from '@/utils/storage'

const getDefaultState = () => {
  return {
    routes: storage.get("PERMISSION_ROUTES")
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_ROUTES: (state, routes) => {
	storage.save('PERMISSION_ROUTES', routes)
    state.routes = routes;
  }
}

const actions = {
  // 用户资源
  userMenus({dispatch, commit}) {
    return new Promise((resolve, reject) => {
		uni.$u.api.menu.listMenu({params: {menuTypeIn: ["M", "C"], displayTypeIn: [0, 2]}}).then(res => {
		  let menu = res.data;
		   
		  let routes = [];
		  for(let i in menu) {
		  	let r = menu[i];
		  	if(r.parentId == 0) {
		  		routes.push(r);
		  	}
		  }
		  for(let i in routes) {
		  	let route = routes[i];
		  	route.children = [];
		  	for(let a in menu) {
		  		let r = menu[a];
		  		if(r.parentId == route.menuId) {
		  			route.children.push(r);
		  		}
		  	}
		  }

		  commit('SET_ROUTES', routes);
					
		  resolve()
		}).catch(error => {
		  reject(error)
		})
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

